/************************************************************************
 * The code is owned by mainframer.cn and Shang Tao
 * Without aproval of mainframer.cn and Shang Tao, remove the copyright
 * infomation is regarded invassion of proprietary copyright
 ***********************************************************************/
package com.mr.qa.action;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.hibernate.Transaction;

import com.mr.qa.UserSession;
import com.mr.qa.UserSessionUtil;
import com.mr.qa.bo.MyLink;
import com.mr.qa.bo.Question;
import com.mr.qa.bo.User;
import com.mr.qa.dao.impl.MyLinkDAO;
import com.mr.qa.dao.impl.QuestionDAO;
import com.mr.qa.dao.impl.UserDAO;
import com.mr.qa.exception.QaException;
import com.mr.qa.form.MyLinkForm;
import com.mr.qa.util.HibernateSessionFactory;

public class MyLinkAction extends BaseAction 
{

    private static final Log logger = LogFactory.getLog(MyLinkAction.class);
    public ActionForward doAction(ActionMapping mapping, ActionForm form,
                            HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        ActionMessages errors = new ActionMessages();
        ActionMessages messages = new ActionMessages();
        ActionForward af = null;
        UserSession session = UserSessionUtil.getUserSession(request);
        MyLinkForm myLinkForm = (MyLinkForm)form;
        String action = this.getAction(request);
        String id = myLinkForm.getId();
        Integer myLinkId = null;
        if(id != null && id.trim().length() > 0)
            myLinkId = new Integer(id);
        Integer page = myLinkForm.getPage();
        if("list".equals(action))
        {
            int count = countAllMyLinks(session.getUserId());
            //System.out.println("mylink count:"+count);
            request.setAttribute("resultSize",count);
            List list = list(page,session.getUserId());
            //System.out.println("mylink size:"+list.size());
            request.setAttribute("mylinks",list);
        }
        else if("add".equals(action) || "addlife".equals(action) || "addtech".equals(action))
        {
            String questionId = myLinkForm.getQuestionId();
            if(questionId == null)
            {
                throw new QaException("Question ID required");
            }
            add(new Integer(questionId), session.getUserId(), new Date());
            String path = mapping.findForward(action).getPath();
            path = path.replace("!?",questionId);
            af = new ActionForward(path);
            af.setRedirect(true);
            ActionMessage message = new ActionMessage("I010");
            messages.add("link",message);
        }
        else if("delete".equals(action))
        {
            delete(myLinkId);
            List list = list(page, session.getUserId());
            request.setAttribute("mylinks",list);
        }
        if(messages.size() > 0)
        {
            this.saveMessages(request.getSession(),messages);
        }
        if(af == null)
            return mapping.findForward(action);
        else
            return af;
    }
    private int countAllMyLinks(Integer userId) throws QaException
    {
        Transaction tx = null;
        int count = 0;
        try
        {
            MyLinkDAO myLinkDAO = new MyLinkDAO();
            tx = HibernateSessionFactory.getSession().beginTransaction();    
            count  = myLinkDAO.countAllMyLinks(userId);
            tx.commit();
        }catch(Exception re)
        {
            throw new QaException(re);
        }
        finally
        {
            HibernateSessionFactory.closeSession();                        
        }
        return count;
    }
    
    private List list(Integer page, Integer userId) throws QaException
    {
        List list = null;
        Transaction tx = null;
        try
        {
            MyLinkDAO myLinkDAO = new MyLinkDAO();
            UserDAO userDAO = new UserDAO();
            myLinkDAO.setPage(page, new Integer(20));
            tx = HibernateSessionFactory.getSession().beginTransaction();    
            User user  = userDAO.findById(userId);
            list = myLinkDAO.findByProperty("mrIaskUser.id", user.getId());
            tx.commit();
        }catch(Exception re)
        {
            if(tx != null)tx.rollback();
            throw new QaException(re);
        } finally
        {
            HibernateSessionFactory.closeSession();                        
        }
        return list;
    }
    
    public boolean add(Integer questionId, Integer uId, Date date) throws QaException
    {
            boolean result = true;
            Transaction tx = null;
            try
            {
                tx = HibernateSessionFactory.getSession().beginTransaction();
                MyLinkDAO myLinkDAO = new MyLinkDAO();
                    if(!myLinkDAO.isAddedBefore(questionId,uId))
                    {
                        UserDAO userDAO = new UserDAO();
                        QuestionDAO questionDAO = new QuestionDAO();
                        User user = userDAO.findById(uId);
                        Question question = questionDAO.findById(questionId);
                        MyLink myLink = new MyLink();
                        myLink.setMrIaskQuestion(question);
                        myLink.setMrIaskUser(user);
                        myLink.setPostDate(date);
                        myLinkDAO.save(myLink);
                        tx.commit();
                    }
            }catch(Exception re)
            {
                    if(tx != null)tx.rollback();
                    throw new QaException(re);
            } finally
            {
                HibernateSessionFactory.closeSession();                        
            }
            return result;
    }
    /**
     * check if user has linked the question
     * @param questionId
     * @param userId
     * @return
     */
    private boolean isAddedBefore(Integer questionId, Integer userId) throws QaException
    {
        Transaction tx = null;
        try
        {
            tx = HibernateSessionFactory.getSession().beginTransaction();
            MyLinkDAO linkDAO = new MyLinkDAO();
            boolean isAddedBefore = linkDAO.isAddedBefore(questionId, userId);
            tx.commit();
            return isAddedBefore;
            /*
            List list = new MyLinkDAO().findByProperty("mrIaskQuestion.id",questionId);
            tx.commit();
            if(list.size() > 0)
                return (MyLink)list.get(0);
            else
                return null;
             */

        }catch(Exception re)
        {
                if(tx != null)tx.rollback();
                throw new QaException(re);
        } finally
        {
            HibernateSessionFactory.closeSession();                        
        }
    }
    /**
     * delete a mylink
     * @param id
     * @return
     * @throws QaException
     */
    public boolean delete(Integer id) throws QaException
    {
        boolean result = true;
        Transaction tx = null;
        try 
        {
            MyLinkDAO myLinkDAO = new MyLinkDAO();                
            tx = HibernateSessionFactory.getSession().beginTransaction();
            MyLink myLink = myLinkDAO.findById(id);
            myLinkDAO.delete(myLink);
            tx.commit();
        }catch(Exception re)
        {
            if(tx != null)tx.rollback();
            throw new QaException(re);
        }finally
        {
            HibernateSessionFactory.closeSession();                        
        }
        return result;
    }
            
}
